package com.tecklab.demo.easyrules;

import com.tecklab.demo.utils.LogConsolehUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.mvel.MVELRule;

@Slf4j
public class MvelRuleTest {

    public static void main(String[] args) {
        // 关闭日志框架日志打印
        LogConsolehUtils.setInfoLevel();
        
        // define rules
        org.jeasy.rules.api.Rule disCountRule = new MVELRule()
                .name("order discount rule")
                .description("if order total money >= 300, then 10% discount")
                .when("order.total >= 300 ")
                .then("System.out.println(\"order.total>=300, 10% discount!\");" +
                        "order.discount = 0.1;")
                .priority(1);

        org.jeasy.rules.api.Rule noDisCountRule = new MVELRule()
                .name("order no discount rule")
                .description("if order total money < 300, no discount!")
                .when("order.total < 300 ")
                .then("System.out.println(\"order.total<300, no discount!\");" +
                        "order.discount=0;")
                .priority(2);

        Rules rules = new Rules();
        rules.register(disCountRule, noDisCountRule);

        RulesEngine rulesEngine = new DefaultRulesEngine();

        // define facts
        Facts facts = new Facts();
        Order order = Order.builder()
                .orderId("001")
                .total(300)
                .build();
        facts.put("order", order);
        rulesEngine.fire(rules, facts);
        log.info("order.discount: {}", order.getDiscount());

        order = Order.builder()
                .orderId("002")
                .total(200)
                .build();
        facts.put("order", order);
        rulesEngine.fire(rules, facts);
        log.info("order.discount: {}", order.getDiscount());
    }
}